#coding=utf-8
from common import get_con
from stutils import set_django_environ
set_django_environ()

from stdj.stock.models import *
import datetime
td = datetime.date.today().isoformat()

def price_compare(p1, p2):
    if p1.end < p2.end:
        return 1
    elif p1.end == p2.end:
        return 0
    else:
        return -1
    
def price_set(share):
    return [ e.price for e in share.exday_set.all()]

def topten_end(share):
    '''按收盘价排序(降序)的topten'''
    ps = price_set(share)
    ps.sort(price_compare)
    r = [[p.exday.date.isoformat(), p.end]for p in ps[:10]]
    return r

def top10_from_db(con, share): 
    sql = 'select * from topten where code = ?'
    cursor = con.cursor()
    cursor.execute(sql, (share.code,))
    data = cursor.fetchall()
    if not data:return None
    r = [[d[3].encode('u8'), d[4]] for d in data]
    return r

def days_between2date(d1, d2):
    d1 = datetime.date( *map(int, d1.split('-')) )
    d2 = datetime.date( *map(int, d2.split('-')) )
    return (d2-d1).days

tb_topten = '''
create table if not exists topten
(id integer primary key,
 code text not null,
 name text not null,
 date text not null,
 price real not null);'''

def initdb():
    con = get_con()
    cursor = con.cursor()
    cursor.execute(tb_topten)
    
    for s in Share.objects.order_by('code'):
        print s
        
        data = topten_end(s)
        for i in data:
            d,p = i
            p = float(str(p))
            print d, p
            cursor.execute('''insert into topten (code,name,date,price)
                            values(?,?,?,?)''',
                            (s.code, s.name, d, p))
            con.commit()
            
        print '\n'

class Topten(object):
    def __init__(self, con):
        self.con = con
        
    def update(self):
        for s in Share.objects.order('code'):
            e = s.exday_today()
            if not e:continue
            end = e.price.end
            des = self.get_top10(s)
            
    def get_top10(self, share):
        sql = 'select * from topten where code = ?'
        cursor = self.con.cursor()
        cursor.execute(sql, (share.code,))
        data = cursor.fetchall()
    
        r = [[d[3].encode('u8'), d[4]] for d in data]
        return r
    
                  
if __name__ == '__main__':
    initdb()
